package com.gk.springauth2auth.service.impl;

import com.alibaba.fastjson.JSON;
import com.gk.springauth2auth.entity.RoleDO;
import com.gk.springauth2auth.entity.UserDO;
import com.gk.springauth2auth.service.RoleService;
import com.gk.springauth2auth.service.UserDetailService;
import com.gk.springauth2auth.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;

/**
 * @Author: poison
 * @Date: 2020/10/11 23:12
 */
@Service
public class UserDetailServiceImpl implements UserDetailService {

    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;

    @Override
    public UserDetails loadUserByUsername(String s) {
        Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
        // 可用性 :true:可用 false:不可用
        boolean enabled = true;
        // 过期性 :true:没过期 false:过期
        boolean accountNonExpired = true;
        // 有效性 :true:凭证有效 false:凭证无效
        boolean credentialsNonExpired = true;
        // 锁定性 :true:未锁定 false:已锁定
        boolean accountNonLocked = true;

        //查询用户信息
        UserDO userDO = userService.loadUserByUserName(s);
        if (userDO==null){
            return null;
        }
        //查询角色信息
        RoleDO roleDO = roleService.loadRoleByUserId(userDO.getId());
        String[] authorities = roleDO.getAuthorities().split(",");
        // 封装用户相关信息
        String principal = JSON.toJSONString(userDO);
        UserDetails userDetails = User.withUsername(principal).password(userDO.getPassword()).authorities(authorities).build();
        return userDetails;
    }

}
